// 工厂列表菜单
import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import {
    Input,
    Button,
    Table,
    Modal,
    Row,
    Col,
    Divider,
    Tag,
    Select,
    Radio,
    DatePicker,
    Cascader,
    message,
    Form,
    Tooltip,
    Switch
} from 'antd';
import {PlusOutlined} from '@ant-design/icons';

import {TableBtn, Search, defaultPagination} from "../publicComponents";
import {get, post} from "../../../utils";
import {config, mUrl} from "../../../config";
import moment from "moment";
import utils from "../../../utils/utils";

const {Option} = Select;
const {RangePicker} = DatePicker;
const FormItem = Form.Item;


const Page = (props) => {
    const [detailsVisible, setDetailsVisible] = useState(false); // 显示厂家信息弹框
    const [row, setRow] = useState({}); // 点击表格按钮要把那一行的数据传送到弹框中
    const [dataSource, setDataSource] = useState([]); // 表格内容信息
    const [searchDetail, setSearchDetail] = useState({}); // 表格内容信息
    const [pagination, setPagination] = useState(Object.assign({}, defaultPagination)); // 表格分页
    const [rankingVisible, setCheckVisible] = useState(false); // 设置排名弹框
    const [openPicVisible, setOpenPicVisible] = useState(false); // 开通画册弹框
    const [options, setOptions] = useState([]); // 分类列表
    const [parentid, setParentId] = useState('');// 当前选中的行
    const [ellipsis, setEllipsis] = useState(false);    
    
    const permissionids = utils.getData('permissionids'); //获取权限id
    
    // 表头信息
    const columns1 = [
        {
            title: '序号',
            align: 'center',
            key: 'orgid',
            dataIndex: 'orgid',
            fixed: true,
            width: 70,
            render: (text, record, index) => ((pagination.pageSize * (pagination.current ? pagination.current - 1 : 0)) + index + 1)
        },
        {
            title: '操作',
            align: 'center',
            fixed: true,
            width: 90,
            ellipsis: true,
            render: (text, record) => {
                return (<TableBtn
                        record={record}
                        onClick={handleTableBtnClick}
                        btns={[
                            {id: 0, name: '编辑'},
                            {id: 1, name: '详情'},
                            {id: 2, name: record.usealbum === 1 ? '关闭画册' : '开通画册'},
                            {id: 3, name: '审核', hidden: (record.orgstate !== 0 && record.orgstate !== -3)},
                            {
                                id: 4,
                                name: record.orgstate === -1 ? '启用' : '停用',
                                hidden: (record.orgstate !== 1 && record.orgstate !== -1)
                            },
                            {id: 5, name: '删除'}
                        ]}
                    />
                );
            }
        },
        {
            title: '工厂编号',
            align: 'center',
            dataIndex: 'orgcode',
            width: 100,
        },
        {
            title: '工厂名称',
            align: 'center',
            dataIndex: 'orgname',
            width: 150,
            render: text => {
                return (
                    <Tooltip placement={'topLeft'} title={text}>
                        {text.length > 10 ? text.substring(0, 10) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '状态',
            align: 'center',
            dataIndex: 'orgstate',
            width: 100,
            render: orgstate => {
                let text = '';
                //(1:已通过；0：待认证；-1：已停用；-2：已删除；-3：未通过)
                switch (orgstate) {
                    case 0:
                        text = '待认证';
                        break;
                    case 1:
                        text = '已通过';
                        break;
                    case -1:
                        text = '已停用';
                        break;
                    case -2:
                        text = '已删除';
                        break;
                    case -3:
                        text = '未通过';
                        break;
                    default:
                }
                return text;
            }
        },
        {
            title: '画册',
            align: 'center',
            dataIndex: 'usealbum',
            width: 100,
            render: usealbum => usealbum === 1 ? '使用中' : '未签约'
        },
        {
            title: '展示图',
            align: 'center',
            width: 120,
            render: (data, record, index) => {
                if (data.imageurl) {
                    if (data.show) {
                        const image = data.imageurl.split(',');
                        return (
                            <div>
                                <img style={{width: 80}} src={image[0]} alt=""/>
                            </div>
                        );
                    } else {
                        return <span
                            style={{color: '#0da8de', cursor: 'pointer'}}
                            onClick={() => showImg(index)}
                            className={'span-selected'}
                        >显示图片</span>;
                    }
                } else {
                    return '--';
                }
            }
        },
        {
            title: '分类',
            align: 'center',
            dataIndex: 'orgClassifyList',
            render: (orgClassifyList = []) => {
                let text = orgClassifyList.map((item) => item.name).join('/') || '--';
                return (
                    <Tooltip placement={'topLeft'} title={text}>
                        {text.length > 15 ? text.substring(0, 10) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '厂家区域',
            align: 'center',
            dataIndex: 'area',
            width: 120,
            render: area => {
                let text = area || '--';
                return (
                    <Tooltip placement={'topLeft'} title={area}>
                        {text.length > 15 ? text.substring(0, 10) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '联系人',
            align: 'center',
            dataIndex: 'linkman',
            width: 100,
            render: linkman => {
                return linkman || '--';
            }
        },
        {
            title: '联系方式',
            align: 'center',
            dataIndex: 'linkphone',
            width: 120,
            render: linkphone => {
                return linkphone || '--';
            }
        },
        {
            title: '地址',
            align: 'center',
            dataIndex: 'orgaddress',
            render: orgaddress => {
                let text = orgaddress || '--';
                return (
                    <Tooltip placement={'topLeft'} title={orgaddress}>
                        {text.length > 15 ? text.substr(0, 10) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '简介',
            align: 'center',
            dataIndex: 'remark',
            render: remark => {
                let text = remark || '--';
                return (
                    <Tooltip placement={'topLeft'} title={remark}>
                        {text.length > 15 ? text.substr(0, 10) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '备注',
            align: 'center',
            dataIndex: 'checkremark',
            render: remark => {
                let text = remark || '--';
                return (
                    <Tooltip placement={'topLeft'} title={remark}>
                        {text.length > 15 ? text.substr(0, 10) + '...' : text}
                    </Tooltip>
                );
            }
        },
    ];
    
    const [userList, setUserList] = useState([]);//厂家信息列表
    useEffect(() => {
        searchTypeList();
        fetch();
    }, []);

    const fetch = (params = {}) => {
        let start = 1;
        if (params.startList > 1) {
            start = params.startList;
        }
        get(mUrl.searchOrganizationList, {
            pageNo: start,
            orgtype: 1,
            pageSize: pagination.pageSize, 
            ...params
        }).then((res) => {
            const {list = [], count = 0} = res.data;
            pagination.total = count;
            setPagination(pagination);
            setDataSource(list);
            setSearchDetail(params);
        });
        get(config.serverUrl2 + '/Show/get_PicOrganizationList', {}).then((res) => {
            setUserList(res.data);
        });
    };

    // 操作点击事件
    const handleTableBtnClick = (id, record) => {
        setRow(record);
        if (id === 0) {
            if(permissionids){
                if (permissionids.indexOf('2021020102')!==-1) {
                    window.onSelectWin({title: '编辑厂家', path: '/main/updateFactory', page: '/main/updateFactory', data: record});
                }else {
                    message.warning('对不起您暂时没有编辑厂家的权限！');
                }
            }
        } else if (id === 1) {
            setDetailsVisible(true);
        } else if (id === 3) {
            if(permissionids) {
                if(permissionids.indexOf('2021020104')!==-1) {
                    setCheckVisible(true);
                }else {
                    message.warning('对不起您暂时没有审核的权限！');
                }
            }
        } else if (id === 2) {
            if (record.usealbum === 1) {
                Modal.confirm({
                    title: '提示',
                    content: '是否要关闭该厂家的画册',
                    onOk: () => {
                        record.enterpriseid = '';
                        record.orgcode = '';
                        handleUpdateDetail({
                            ...record,
                            usealbum: 0,
                        }, () => {
                            message.info('取消成功');
                        });
                    }
                });
            } else {
                setOpenPicVisible(true);
            }
        } else if (id === 4 || id === 5) {
            if (permissionids) {
                if (permissionids.indexOf('2021020103')!==-1) {
                    let text = record.orgstate === -1 ? '启用' : '停用';
                    let orgstate = record.orgstate === -1 ? 1 : -1;
                    if (id === 5) {
                        text = '删除';
                        orgstate = -2;
                    }
                    Modal.confirm({
                        title: '提示',
                        content: '是否要' + text + '该厂家',
                        onOk: () => {
                            handleUpdateDetail({
                                ...record,
                                orgstate,
                            }, () => {
                                message.info(text + '成功');
                            });
                        }
                    });
                }else {
                    message.warning('对不起您没有停用、启用和修改的权限！');
                }
            }
        }
    };
    
    // 查询分类
    const searchTypeList = () => {
        get(mUrl.searchAllClassify, {}).then((res) => {
            const data = res.data.map((item) => {
                const list = item.subClassifyList.map((sItem) => {
                    return {
                        value: sItem.classifyid,
                        label: sItem.name,
                    };
                });
                return {
                    value: item.classifyid,
                    label: item.name,
                    children: list
                };
            });
            setOptions(data);
        });
    };

    // const onSearch = (value) => {
    //     console.log(value);
    //     if (value.sodji && value.sodji.length) {
    //         value.classifyid = value.sodji[value.sodji.length - 1];
    //     } else {
    //         value.classifyid = undefined;
    //     }
    //     delete value.sodji;
    //     fetch(value);
    // };
    
    // 预览图片
    const showImg = (index) => {
        dataSource[index].show = true;
        setDataSource(Object.assign([], dataSource));
    };

    // 搜索
    const onSearch = (value) => {
        if (value.sodji) {
            value.classifyid = value.sodji;
        } else {
            value.classifyid = undefined;
        }
        delete value.sodji;
        fetch(value);
    };

    // 重置
    const onReset = () => {
        fetch({});
    };

    // 导出
    const onExcel = () => {
        window.location.href = utils.getUrl(config.serverUrl + mUrl.get_exportOrganizationList, searchDetail);
    };

    const handleTableChange = (page) => {
        pagination.current = page.current;
        pagination.pageSize = page.pageSize;
        setPagination(pagination);
        fetch({
            ...searchDetail,
            startList: pagination.current
        });
    };

    const handleUpdateDetail = async (value, callback) => {
        const data = Object.assign({}, row, value);

        const res = await post(mUrl.updateOrganization, data);
        if (res.state === 1) {
            callback();
            fetch(searchDetail);
        }
    };

    // 展开更多操作事件
    const handleEllipsisChange = (enable) => {
        setEllipsis(enable);
    };

    const handleSetColumn = (enable) => {
        const columns = columns1;
        if (!enable) {
            columns[1].width = 90;
            columns[1].ellipsis = true;
        } else {
            columns[1].width = 250;
            columns[1].ellipsis = false;
        }
        return columns;
    };

    const columns = handleSetColumn(ellipsis);
    
    // 新增厂家
    const add = () => {
        if (permissionids) {
            if (permissionids.indexOf('2021020101') !== -1) {
                window.onSelectWin({
                    title: '新增厂家', 
                    path: '/main/addFactory', 
                    page: '/main/addFactory'
                });
            } else {
                message.warning('对不起您暂时没有新增厂家的权限！');
            }
        }
    };
    
    // 数据渲染
    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>厂家管理 / 厂家列表</p></label>
            <Search
                onSearch={onSearch}
                onReset={onReset}
                searchData={[
                    // {
                    //     key: 'sodji', name: '分类', component: (
                    //         <Cascader
                    //             placeholder="请选择"
                    //             showSearch={true}
                    //             options={options}/>
                    //     ), span: 4
                    // },
                    {
                        span: 4, key: 'sodji', name: '分类', component: (
                            <Select
                                placeholder="请选择"
                                showSearch={true}
                                options={options}/>
                        )
                    },
                    {
                        span: 6, key: 'orgname', name: '工厂', component: (
                            <Input allowClear placeholder={'工厂名称/联系人/联系方式'}/>
                        )
                    },
                    {
                        span: 4, key: 'orgstate', name: '状态', component: (
                            <Select placeholder={'请选择'}>
                                <Option value={''}>全部</Option>
                                <Option value={'1'}>已通过</Option>
                                <Option value={'0'}>待认证</Option>
                                <Option value={'-1'}>已停用</Option>
                                <Option value={'-3'}>未通过</Option>
                            </Select>
                        )
                    }
                ]}
                otherBtns={[{name: '导出', onClick: () => onExcel()}]}
            />
            <Button
                type={'primary'}
                style={{margin: '0 0 10px 0'}}
                onClick={add}
            >
                <PlusOutlined/>新增厂家
            </Button>
            <div style={{display: 'inline-block', marginLeft: 20,}}>
                <span>展开更多操作:</span>
                <Switch
                    style={{marginLeft: 5, marginBottom: 3}}
                    checkedChildren="开启"
                    unCheckedChildren="关闭"
                    checked={ellipsis}
                    onChange={handleEllipsisChange}
                />
            </div>
            <Table
                rowKey={(record) => {
                    return record.orgid;
                }}
                scroll={{x: 2000, y: 600}}
                dataSource={dataSource}
                columns={columns}
                bordered
                pagination={pagination}
                onChange={handleTableChange}
                rowClassName={(record) => {
                    if (record.orgid === parentid) {
                        return 'table-select-type';
                    } else {
                        return 'table-type';
                    }
                }}
                onRow={record => {
                    return {
                        onClick: event => {
                            setParentId(record.orgid);
                        },
                    };
                }}
            />
            <Details
                row={row}
                detailsVisible={detailsVisible}
                setDetailsVisible={setDetailsVisible}
            />
            <Check
                rankingVisible={rankingVisible}
                setCheckVisible={setCheckVisible}
                submit={handleUpdateDetail}
            />
            <OpenPic
                submit={handleUpdateDetail}
                openPicVisible={openPicVisible}
                setOpenPicVisible={setOpenPicVisible}
                userList={userList}
            />
        </div>
    );
};

// 点击表格中的详情的弹框
const Details = (props) => {
    const {detailsVisible, onOk, setDetailsVisible, row = {}} = props;

    const ImageurlRow = (imageurl) => {
        const image = imageurl.split(',');
        return (
            <div style={{display: 'flex', flexWrap: 'wrap',justifyContent:'center'}}>
                {
                    image.map((item, index) => {
                        return <img
                            style={{width:'70%',height:'60%'}}    
                            key={'img' + index} 
                            src={item} alt=""/>;
                    })
                }
            </div>
        );
    };

    const classRow = (list) => {
        let text = list.map((item) => item.name).join('/');
        return text || '--';
    };

    return (
        <Modal
            visible={detailsVisible}
            onCancel={_ => setDetailsVisible(false)}
            onOk={onOk}
            footer={false}
            title='厂家详情'
            width='60%'
        >
            <Row>
                <Col span={24}>
                    主图：{row.imageurl && ImageurlRow(row.imageurl)}
                </Col>
            </Row>
            <Divider/>
            <Row>
                <Col span={24}>
                    营业执照：{row.businessurl && ImageurlRow(row.businessurl)}
                </Col>
            </Row>
            <Divider/>
            <Row>
                <Col span={12}>
                    分类：
                    {row.orgClassifyList && classRow(row.orgClassifyList)}
                </Col>
                <Col span={12}>
                    工厂名称：{row.orgname}
                </Col>
            </Row>
            <Divider/>
            <Row>
                <Col span={12}>
                    联系人：{row.linkman}
                </Col>
                <Col span={12}>
                    账号：{row.appletslogin}
                </Col>
            </Row>
            <Divider/>
            <Row>
                <Col span={12}>
                    联系方式：{row.linkphone}
                </Col>
                <Col span={12}>
                    标签：
                    {
                        row.orgLabelList &&
                        row.orgLabelList.map((item, index) => {
                            return <Tag color='pink' key={'label' + index}>{item.labelname}</Tag>;
                        })
                    }
                </Col>
            </Row>
            <Divider/>
            <Row>
                <Col span={24}>
                    地址：{row.orgaddress}
                </Col>
            </Row>
            <Divider/>
            <Row>
                <Col span={24}>
                    简介：{row.remark}
                </Col>
            </Row>
            <Divider/>
            <Row>
                <Col span={24}>
                    介绍图：<img src={row.detailurl} alt=""/>
                </Col>
            </Row>
            <Divider/>
            <Row>
                <Col span={24}>
                    微信二维码：<img src={row.qrcordurl} alt=""/>
                </Col>
            </Row>
            <Divider/>
            <Row>
                <Col span={24}>
                    视频：{row.videourl && <video width="240" height="160" controls>
                    <source src={row.videourl}
                            type="video/ogg"/>
                    <source src={row.videourl}
                            type="video/mp4"/>
                    <source src={row.videourl}
                            type="video/webm"/>
                    <object src={row.videourl}
                            width="240"
                            height="160">
                        <embed width="240" height="160"
                               src={row.videourl}/>
                    </object>
                </video>
                }
                </Col>
            </Row>
        </Modal>
    );
};

// 点击表格中的审核
const Check = (props) => {
    const {rankingVisible, setCheckVisible} = props;
    const [checkremark, setCheckremark] = useState(null);
    const [orgstate, setOrgstate] = useState(null);
  
    const handleSubmit = () => {
        if (!orgstate) {
            message.error('请选择审核是否通过');
            return;
        }
        props.submit({
            orgstate,
            checkremark
        }, () => {
            message.success('审核成功');
            setCheckVisible(false);
        });
    };
    return (
        <Modal
            title='审核'
            visible={rankingVisible}
            onCancel={_ => setCheckVisible(false)}
            onOk={() => handleSubmit()}
        >
            <Row>
                <Col span={24}>
                    <FormItem
                        required
                        label={'审核'}
                        labelCol={6}
                        wrapperCol={18}>
                        <Radio.Group value={orgstate} onChange={(e) => setOrgstate(e.target.value)}>
                            <Radio value={'1'}>通过</Radio>
                            <Radio value={'-3'}>不通过</Radio>
                        </Radio.Group>
                    </FormItem>
                </Col>
                <Col span={24}>
                    <FormItem
                        label={'备注'}
                        name='remark'
                        labelCol={6}
                        wrapperCol={18}>
                        <Input.TextArea
                            rows={3}
                            style={{width: '80%'}} value={checkremark}
                            onChange={(e) => setCheckremark(e.target.value)}/>
                    </FormItem>
                </Col>
            </Row>
        </Modal>
    );
};

// 点击表格中的开通画册
const OpenPic = (props) => {
    const [form] = Form.useForm();
    const {openPicVisible, setOpenPicVisible, userList} = props;
    //const [usealbum, setUsealbum] = useState(null);
    const [time, setTime] = useState(null);
    const [orgcode, setOrgcode] = useState(null);
    const [enterpriseid, setEnterpriseid] = useState(null);

    useEffect(() => {
        if (openPicVisible) {
            // setUsealbum(null);
            setOrgcode(null);
            setTime(null);
            setEnterpriseid(null);
            form.setFieldsValue({
                usealbum: "1"
            });
        }
    });

    // form.submit = async() => {
    //     if (!time) {
    //         message.error('请选择时间');
    //         return;
    //     }
    //     if (!usealbum) {
    //         message.error('请选择是否开通');
    //         return;
    //     }
    //     if (!enterpriseid) {
    //         message.error('请输入厂家编号');
    //         return;
    //     }
    //     const quseryendtime = moment(time[0]._d).format('YYYY-MM-DD');
    //     const quserystrattime = moment(time[1]._d).format('YYYY-MM-DD');
    //     props.submit({
    //         usealbum, //是否开通
    //         quseryendtime, //结束时间
    //         quserystrattime, //开始时间
    //         enterpriseid
    //     }, () => {
    //         message.success('设置成功');
    //         setOpenPicVisible(false);
    //     });
    // };

    const onFinish = (value) => {
        if (!value.time) {
            message.error('请选择时间');
            return;
        }
        if (!value.usealbum) {
            message.error('请选择是否开通');
            return;
        }
        if (!value.enterpriseid) {
            message.error('请输入厂家编号');
            return;
        } else {
            value.enterpriseid = JSON.parse(value.enterpriseid);
            value.orgcode = value.enterpriseid.orgcode;
            value.enterpriseid = value.enterpriseid.enterpriseid;
        }
        const quseryendtime = moment(value.time[0]._d).format('YYYY-MM-DD');
        const quserystrattime = moment(value.time[1]._d).format('YYYY-MM-DD');
        const usealbum = value.usealbum;
        const enterpriseid = value.enterpriseid;
        const orgcode = value.orgcode;
        props.submit({
            orgcode,
            usealbum, //是否开通
            quseryendtime, //结束时间
            quserystrattime, //开始时间
            enterpriseid
        }, () => {
            message.success('设置成功');
            setOpenPicVisible(false);
        });
    };

    return (
        <Modal
            title='开通画册'
            visible={openPicVisible}
            onOk={() => form.submit()}
            onCancel={_ => setOpenPicVisible(false)}
        >
            <Form onFinish={onFinish} form={form}>
                <Row>
                    <Col span={24}>
                        <FormItem name={'usealbum'}
                                  required
                                  label={'是否开通画册'}>
                            <Radio defaultChecked value={'1'}>是</Radio>
                        </FormItem>
                    </Col>
                </Row>
                <Divider/>
                <Row>
                    <Col span={24}>
                        <FormItem name={'enterpriseid'} required label={'厂家编号'}>
                            <Select placeholder={'请选择厂家编号/厂家名称'} onChange={(value) => {
                                setEnterpriseid(value);
                                //setOrgcode(userList.find(item => item.enterpriseid === value).orgcode);
                            }}>
                                {
                                    userList.map((item, index) => {
                                        return <Option
                                            key={index}
                                            //value={item.enterpriseid}
                                            value={JSON.stringify({
                                                enterpriseid: item.enterpriseid,
                                                orgcode: item.orgcode
                                            })}
                                        >
                                            {item.orgcode}/{item.showname}
                                        </Option>;
                                    })
                                }
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Divider/>
                <Row>
                    <Col span={24}>
                        <FormItem name={'time'} required label={'有效期'}>
                            <RangePicker value={time} onChange={(date) => setTime(date)}/>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
        </Modal>
    );
};

const mapStateToProps = (state) => {
    return {
        ...state.appReducer, // 全局的reducers
    };
};

export default connect(mapStateToProps)(Page);